# src/config_loader.py

"""
配置加载工具 - 从YAML文件加载配置
"""

import os
import yaml

def load_config(config_path=None):
    """
    加载YAML配置文件
    
    Args:
        config_path: 配置文件路径，默认为项目根目录的config.yaml
        
    Returns:
        dict: 配置字典
    """
    if config_path is None:
        # 自动查找config.yaml
        current_dir = os.path.dirname(os.path.abspath(__file__))
        project_root = os.path.dirname(current_dir)
        config_path = os.path.join(project_root, 'config.yaml')
    
    if not os.path.exists(config_path):
        raise FileNotFoundError(f"配置文件不存在: {config_path}")
    
    with open(config_path, 'r', encoding='utf-8') as f:
        cfg = yaml.safe_load(f)
    
    return cfg


def get_value(cfg, key_path, default=None):
    """
    从嵌套配置字典中获取值
    
    Args:
        cfg: 配置字典
        key_path: 键路径，如 'training.batch_size'
        default: 默认值
        
    Returns:
        配置值
    """
    keys = key_path.split('.')
    value = cfg
    
    for key in keys:
        if isinstance(value, dict) and key in value:
            value = value[key]
        else:
            return default
    
    return value

